package com.study.example.gameserver.module.scene.bt.node;

import com.sparrow.common.ai.behaviortree.BehaviorContext;
import com.sparrow.common.ai.behaviortree.def.BTNodeStatus;
import com.sparrow.common.ai.behaviortree.node.impl.ActionNode;
import com.study.example.gameserver.module.scene.domain.SceneMap;
import com.study.example.gameserver.module.scene.entity.IPlayerEntity;
import com.study.example.gameserver.module.scene.entity.impl.Monster;
import com.study.example.gameserver.module.scene.service.SceneService;
import java.util.Map;

/**
 * 被攻击后进行反击
 */
public class CounterAttackEnemy extends ActionNode {

    @Override
    public BTNodeStatus tick(BehaviorContext context, long now, long delta) {
        Monster monster = context.getOwner();
        if (monster == null) {
            return BTNodeStatus.FAILURE;
        }

        SceneMap sceneMap = context.get("SceneMap", SceneMap.class);
        if (sceneMap == null) {
            return BTNodeStatus.FAILURE;
        }

        // 从最近攻击过自己的玩家中选出一个目标
        IPlayerEntity target = null;
        if (monster.getAttackMeIds().size() > 0) {
            for (Map.Entry<Long, Long> e : monster.getAttackMeIds().entrySet()) {
                long playerId = e.getKey();
                long lastAttackTime = e.getValue();
                // 仅反击 2 秒内打过我的玩家
                if (lastAttackTime + 2000 >= now) {
                    target = sceneMap.getPlayers().get(playerId);
                    break;
                }
            }
        }

        if (target == null) {
            // 没有可以反击的目标
            return BTNodeStatus.FAILURE;
        }

        // 检查攻击冷却
        Long lastCounterTime = context.get("LastCounterTime", Long.class);
        if (lastCounterTime == null || System.currentTimeMillis() - lastCounterTime >= 1000) {
            context.put("LastCounterTime", System.currentTimeMillis());

            SceneService sceneService = context.get("SceneMapService", SceneService.class);
            sceneService.monsterAttack(sceneMap, monster, target);

            if (!target.isAlive()) {
                monster.setTargetId(0L);
            }
        }

        return BTNodeStatus.RUNNING;
    }

    @Override
    public void initParams(String name, String value) {
        // 可扩展参数，例如反击冷却时间、反击范围等
    }

    @Override
    public String toString() {
        return "CounterAttackEnemy";
    }
}
